package com.zimi.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zimi.mapper.SysOrgExtendMapper;
import com.zimi.mapper.SysOrgMapper;
import com.zimi.mapper.SysPostPrivilegeMapper;
import com.zimi.model.*;
import com.zimi.util.CommonUtil;
import com.zimi.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 岗位功能授权表 Service
 *
 * @author lnintr
 * @since 2019-05-22
 */
@Service
public class SysPostPrivilegeService {
    @Autowired
    private SysOrgExtendMapper sysOrgExtendMapper;

    @Autowired
    private SysOrgMapper sysOrgMapper;

    @Autowired
    private SysPostPrivilegeMapper sysPostPrivilegeMapper;

    @Autowired
    private CommonUtil commonUtil;
    /*
    @author lxc
     * 取得机构和岗位树结构信息
     * */
    public List<SysOrgExtend> getPostTree(SysOrgExtend record) {
        List<SysOrgExtend> result = new ArrayList<>();

        Map map = commonUtil.getOrgList();
        // 1)取得机构一览
        List<SysOrgExtend> list = sysOrgExtendMapper.getMineOrgList(map);

        if (list != null && list.size() > 0) {
            // 2)取得岗位一览
            List<SysOrgExtend> postList = sysOrgExtendMapper.selectOrgPostList(map);

            if (postList != null && postList.size() > 0) {
                for (SysOrgExtend soe : postList) {
                    soe.setId(soe.getPostId());
                    soe.setName(soe.getPostName());
                    soe.setFlag(3);
                    result.add(soe);
                }
            }

            result.addAll(list);

            // 3)取得并合并机构分类
            List<SysOrgExtend> orgCateList = sysOrgExtendMapper.getMineOgnCateList((List<Integer>) map.get("ognIdList"));

            if (orgCateList != null && orgCateList.size() > 0) {
                result.addAll(orgCateList);
            }
        }

        return result;
    }

    /**
     * @author wh
     * @desc 获取上级岗位数据
     */
    public List<SysOrgExtend> getSupPostTree(SysOrgExtend record) { //此代码在数据库中有bug
        List<SysOrgExtend> result = new ArrayList<>();
        //1 取数据
        List<SysOrgExtend> list = getPostTree(record);
        List<SysPostSuperiors> superiorsList = new SysPostSuperiors().selectList(new LambdaQueryWrapper<SysPostSuperiors>().eq(SysPostSuperiors::getOriginOrgId,record.getOrgId()).eq(SysPostSuperiors::getPostId,record.getPostId()));

        //2 准备好Map 和list
        Map supMap = new HashMap();
        List<String> supList = new ArrayList<>();
        if(superiorsList != null && superiorsList.size() > 0){
            for(SysPostSuperiors i : superiorsList){
                supMap.put(String.format("%s-%s",i.getOrgId(),i.getSuperiorsId()),i);
                supList.add(String.format("%s-%s",i.getOrgId(),i.getSuperiorsId()));
            }
        }

        //3 对树结构中已有的数据添加id和 updateTime
        if(list != null && list.size()> 0){
            for(SysOrgExtend soe : list){
                String tmpStr = String.format("%s-%s",soe.getOrgId(),soe.getPostId());
                if(supList.contains(tmpStr)){
                    SysPostSuperiors tmpSuper = (SysPostSuperiors)supMap.get(tmpStr);
                    soe.setSuperiorsId(tmpSuper.getId()); //标注：superiors表的id赋给orgExtend中的superiorsId
                    soe.setUpdateTime(tmpSuper.getUpdateTime());
                }else{
                    soe.setSuperiorsId(null);
                    soe.setUpdateTime(null);
                }
                result.add(soe);
            }
        }

        return result ;
    }

    /**
     * @author wh
     * @desc 获取部门数据
     */
    public List<SysOrgExtend> getLeaderList(SysOrgExtend record) {
        List<SysOrgExtend> result = new ArrayList<>();
        //1 取出机构岗位树结构的数据 和 取出 leader表中一个树节点的数据
        List<SysOrgExtend> list = getPostTree(record);
        List<SysOrgLeader> orgLeaders = new SysOrgLeader().selectList(new LambdaQueryWrapper<SysOrgLeader>().eq(SysOrgLeader::getOriginOrgId,record.getOrgId()));

        Map leaderMap = new HashMap();
        List<String> leaderList = new ArrayList<>();

        //2 事先预备好leader表的map 和 list
        if(orgLeaders != null && orgLeaders.size() > 0){
            for(SysOrgLeader j : orgLeaders){
                leaderMap.put(String.format("%s-%s",j.getOrgId(),j.getPostId()),j);
                leaderList.add(String.format("%s-%s",j.getOrgId(),j.getPostId()));
            }
        }

        //3 如果机构岗位树的orgId-postId在leaderList中，则把加入leader表中id和updataTime加入树结构中，默认岗位在前台去加
        if(list != null && list.size()> 0){
            for(SysOrgExtend soe : list){
                String tmpStr = String.format("%s-%s",soe.getOrgId(),soe.getPostId());
                if(leaderList.contains(tmpStr)){
                    SysOrgLeader tmpLeader = (SysOrgLeader)leaderMap.get(tmpStr);
                    soe.setFunctionId(tmpLeader.getId()); //标注：leader表的id赋给orgExtend中的functionId
                    soe.setUpdateTime(tmpLeader.getUpdateTime());
                }else{
                    soe.setFunctionId(null);
                    soe.setUpdateTime(null);
                }
                result.add(soe);
            }
        }

        return result ;
    }




    /**
     * 取得岗位和人员树信息
     * @author wh
     * @return
     */
    public List<SysOrgExtend> getUserTree(SysOrgExtend record){
        List<SysOrgExtend> result = new ArrayList<>();

        List<SysOrg> orgList = sysOrgMapper.selectList(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getOrgState, 1));
        SysOrgExtend tmpOrgExtend = null;

        if (orgList != null && orgList.size() > 0) {
            for (SysOrg so : orgList) {
                tmpOrgExtend = new SysOrgExtend();

                tmpOrgExtend.setFlag(1);
                tmpOrgExtend.setId(so.getId());
                tmpOrgExtend.setName(so.getOrgName());
                tmpOrgExtend.setOrgId(so.getId());
                tmpOrgExtend.setParentId(so.getOrgPid() == null ? 0 : so.getOrgPid());
                tmpOrgExtend.setOrgName(so.getOrgName());
                tmpOrgExtend.setChoiceFlag(false);

                result.add(tmpOrgExtend);
            }

            List<SysOrgExtend> list = sysOrgExtendMapper.selectOrgPostList(null);

            if (list != null && list.size() > 0) {
                for (SysOrgExtend soe : list) {
                    soe.setId(soe.getPostId());
                    soe.setName(soe.getPostName());
                    soe.setFlag(1);
                    soe.setChoiceFlag(false);
                    soe.setParentId(soe.getOrgId());
                    result.add(soe);
                }
            }

            List<SysOrgExtend> userList = sysOrgExtendMapper.selectPostUserList(null);

            if (userList != null && userList.size() > 0) {
                for (SysOrgExtend soe : userList) {
                    soe.setId(soe.getId());
                    soe.setName(soe.getName());
                    soe.setFlag(2);
                    soe.setIconType("user");
                    soe.setChoiceFlag(false);
                    soe.setParentId(soe.getParentId());
                    result.add(soe);
                }
            }
        }

        return result;
    }

    /*
     * 取得权限和岗位信息
     * */
    public Object getFunctionlistByPost(SysOrgExtend sysOrgExtend) {
        // 1)取得所有功能
        List<SysOrgExtend> list = sysOrgExtendMapper.selectFunctionList(sysOrgExtend);

        if (list != null && list.size() > 0) {
            // 2)取得所有功能信息
            List<SysPostPrivilege> listFunction = sysPostPrivilegeMapper.selectList(new QueryWrapper<SysPostPrivilege>().lambda().eq(SysPostPrivilege::getPostId, sysOrgExtend.getPostId()).eq(SysPostPrivilege::getOrgId, sysOrgExtend.getOrgId()));
            Map<Integer, SysPostPrivilege> roleMap = null;

            if (listFunction != null && listFunction.size() > 0) {
                roleMap = new HashMap<>();
                for (SysPostPrivilege srpl : listFunction) {
                    roleMap.put(srpl.getFunctionId(), srpl);
                }
            }

            // 设置选中标志的值
            for (SysOrgExtend soe : list) {
                if (roleMap != null) {
                    SysPostPrivilege sysPostPrivilege = (SysPostPrivilege) roleMap.get(soe.getFunctionId());

                    if (sysPostPrivilege != null) {
                        soe.setId(sysPostPrivilege.getId());
                        soe.setUpdateTime(sysPostPrivilege.getUpdateTime());

                        if (sysPostPrivilege.getPrivilegeState() == 1) {
                            soe.setChoiceFlag(true);
                        } else {
                            soe.setChoiceFlag(false);
                        }
                    } else {
                        soe.setChoiceFlag(false);
                        soe.setId(0);
                    }
                } else {
                    soe.setChoiceFlag(false);
                    soe.setId(0);
                }
            }
        }

        return list;
    }

    @Transactional
    public void saveFunctionPost(List<SysOrgExtend> sysOrgExtends, int flag) {
        List<Integer> idList = new ArrayList<>();
        if (sysOrgExtends != null && sysOrgExtends.size() > 0) {

            SysOrgPostPair sysOrgPostPair = new SysOrgPostPair();
            sysOrgPostPair.setOrgId(sysOrgExtends.get(0).getOrgId());
            sysOrgPostPair.setPostId(sysOrgExtends.get(0).getPostId());

            SysPostPrivilege tmpOrgExtend = null;

            for (SysOrgExtend soe : sysOrgExtends) {
                idList.add(soe.getFunctionId());
            }

            // 1）对要修改的对象加行锁
            List<SysPostPrivilege> results = sysPostPrivilegeMapper.selectListForUpdate(sysOrgPostPair);

            Map<Integer, SysPostPrivilege> resMap = null;

            if (results != null && results.size() > 0) {
                resMap = new HashMap<>();

                for (SysPostPrivilege spp : results) {
                    resMap.put(spp.getFunctionId(), spp);
                }
            }

            SysUser user = UserUtil.getUser();
            Date updateTime = new Date();

            // 2)所属权限创建或修改
            for (SysOrgExtend soe : sysOrgExtends) {
                if (resMap != null) {
                    tmpOrgExtend = resMap.get(soe.getFunctionId());

                    // 3）判断该数据已经被改过没有
                    if (tmpOrgExtend != null) {
                        if (tmpOrgExtend.getUpdateTime() != null) {
                            if (soe.getUpdateTime() != null && soe.getUpdateTime().getTime() != tmpOrgExtend.getUpdateTime().getTime()) {
                                throw new RuntimeException("修改数据失败，数据已经被其他用户改过。");
                            }
                        }

                        tmpOrgExtend.setUpdateUser(user.getId());
                        tmpOrgExtend.setUpdateTime(updateTime);
                        tmpOrgExtend.setPrivilegeState(flag);
                        tmpOrgExtend.updateById();
                    } else {
                        tmpOrgExtend = new SysPostPrivilege();

                        tmpOrgExtend.setCreateUser(user.getId());
                        tmpOrgExtend.setCreateTime(updateTime);
                        tmpOrgExtend.setPrivilegeState(flag);
                        tmpOrgExtend.setPostId(sysOrgPostPair.getPostId());
                        tmpOrgExtend.setOrgId(sysOrgPostPair.getOrgId());
                        tmpOrgExtend.setFunctionId(soe.getFunctionId());

                        tmpOrgExtend.insert();
                    }
                } else {
                    tmpOrgExtend = new SysPostPrivilege();

                    tmpOrgExtend.setCreateUser(user.getId());
                    tmpOrgExtend.setCreateTime(updateTime);
                    tmpOrgExtend.setPrivilegeState(flag);
                    tmpOrgExtend.setPostId(sysOrgPostPair.getPostId());
                    tmpOrgExtend.setOrgId(sysOrgPostPair.getOrgId());
                    tmpOrgExtend.setFunctionId(soe.getFunctionId());

                    tmpOrgExtend.insert();
                }
            }
        }
    }
}
